package 尚硅谷.juc.test6;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

public class Test6 {
    static AtomicStampedReference<Integer> atomicReference=new AtomicStampedReference<>(100,1);
    public static void main(String[] args) {
        new Thread(()->{
            try {
                //获取版本号
                TimeUnit.SECONDS.sleep(1);
                //修改原子引用数据，并修改版本号+1
                atomicReference.compareAndSet(100,101,atomicReference.getStamp(),atomicReference.getStamp()+1);
                //修改原子引用数据，并修改版本号+1
                atomicReference.compareAndSet(101,100,atomicReference.getStamp(),atomicReference.getStamp()+1);
                //最终版本号是3
                System.out.println(Thread.currentThread().getName()+"最终版本号："+atomicReference.getStamp());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();
        new Thread(()->{
            try {
                //t2线程拿到的版本是1
                int stamp = atomicReference.getStamp();
                TimeUnit.SECONDS.sleep(5);
                //此时t1执行完，虽然原子引用过的值是100，但是此时的版本号是3，你再拿stamp进行版本对比肯定返回flase
                boolean b = atomicReference.compareAndSet(100, 2019, stamp, stamp + 1);
                System.out.println(b);
                System.out.println(Thread.currentThread().getName()+"拿到的版本号："+stamp);
                System.out.println("实际版本号："+atomicReference.getStamp());
                System.out.println(atomicReference.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t2").start();
    }
}
